from odoo import models, fields, api

LOG_TYPE = [('issue', '发放'), ('use', '使用'), ('expired', '过期'), ('active', '生效')]


class RpMarketingActionLog(models.Model):
    _name = 'rp.marketing.action.log'
    _description = '动作记录'
    _rec_name = 'code'

    # 公共属性
    code = fields.Char(string='序列号', default='RP_MAL/****', copy=False, index=True)
    root_category = fields.Selection(string='分类', selection=LOG_TYPE, copy=False, index=True)
    rp_customer_id = fields.Many2one(string='客户', comodel_name='rp.customer', copy=False, index=True)
    customer_coupon_ids = fields.Many2many(string='优惠券', comodel_name='rp.customer.coupon', column1='rp_marketing_action_log_id', column2='rp_customer_coupon_id', relation='rp_marketing_action_log_customer_coupon_rel', copy=False)

    # 发券信息
    operation_person = fields.Many2one(string='操作人', comodel_name='res.users', copy=False, index=True)
    change_display = fields.Char(string='变化', copy=False)
    funds_change = fields.Float(string='资金变化')
    change_type = fields.Selection(string='变化类型', selection=[('add', '+'), ('subtract', '-')], copy=False)
    data_create = fields.Datetime(string='创建时间', default=fields.Datetime.now(), copy=False)

    # 优惠券使用记录
    ship_order_id = fields.Many2one(string='订单', comodel_name='rp.ship.order', copy=False)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.marketing.action.log') or '/'
            if 'change_type' in vals.keys() and 'funds_change' in vals.keys():
                if vals['change_type'] and vals['funds_change']:
                    if vals['change_type'] == 'add':
                        vals['change_display'] = '+ {}€'.format(vals['funds_change'])
                    if vals['change_type'] == 'subtract':
                        vals['change_display'] = '- {}€'.format(vals['funds_change'])
        return super(RpMarketingActionLog, self).create(vals_list)
